# 导入tkinter库，用于创建GUI
import tkinter as tk
from tkinter import messagebox

# 定义一个函数来执行计算
def calculate():
    try:
        # 获取用户输入的两个数字
        num1 = float(entry_num1.get())
        num2 = float(entry_num2.get())
        # 获取用户选择的运算符
        operation = operation_var.get()

        # 根据运算符执行相应的计算
        if operation == "+":
            result = num1 + num2
        elif operation == "-":
            result = num1 - num2
        elif operation == "*":
            result = num1 * num2
        elif operation == "/":
            if num2 == 0:  # 检查除数是否为零
                messagebox.showerror("错误", "除数不能为零！")
                return
            result = num1 / num2
        else:
            messagebox.showerror("错误", "无效的运算符！")
            return

        # 显示计算结果
        result_label.config(text=f"结果: {result}")
    except ValueError:  # 如果输入的不是数字，提示错误
        messagebox.showerror("错误", "请输入有效的数字！")

# 创建主窗口
root = tk.Tk()
root.title("简单计算器")  # 设置窗口标题

# 创建输入框和标签
label_num1 = tk.Label(root, text="第一个数字:")
label_num1.grid(row=0, column=0, padx=10, pady=10)
entry_num1 = tk.Entry(root)
entry_num1.grid(row=0, column=1, padx=10, pady=10)

label_num2 = tk.Label(root, text="第二个数字:")
label_num2.grid(row=1, column=0, padx=10, pady=10)
entry_num2 = tk.Entry(root)
entry_num2.grid(row=1, column=1, padx=10, pady=10)

# 创建运算符选择框
operation_var = tk.StringVar(value="+")  # 默认选择加法
operations = ["+", "-", "*", "/"]
operation_label = tk.Label(root, text="选择运算符:")
operation_label.grid(row=2, column=0, padx=10, pady=10)
operation_menu = tk.OptionMenu(root, operation_var, *operations)
operation_menu.grid(row=2, column=1, padx=10, pady=10)

# 创建计算按钮
calculate_button = tk.Button(root, text="计算", command=calculate)
calculate_button.grid(row=3, column=0, columnspan=2, padx=10, pady=10)

# 创建结果标签
result_label = tk.Label(root, text="结果: ")
result_label.grid(row=4, column=0, columnspan=2, padx=10, pady=10)

# 运行主循环
root.mainloop()